﻿using System;
using System.Threading.Tasks;
using System.Transactions;
using HengTong.Model.Db.Hr.Bill;
using WalkingTec.Mvvm.Core;
using Microsoft.Extensions.DependencyInjection;
using HengTong.Model.Services;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Models;
using TiaoTaoHelper.Wtm.Interfaces;
using IFlow = TiaoTaoHelper.Wtm.Models.IFlow;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;


namespace HengTong.ViewModel.Daily.SysDailyOutFactoryRequestBillVms
{
    public partial class SysDailyOutFactoryRequestBillVm : CrudVm<SysDailyOutFactoryRequestBill>
    {

        public SysDailyOutFactoryRequestBillVm()
        {
            SetInclude(x => x.Group);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            if (Entity is IBill bill)
            {
                Entity.BillStatus = BillStatus.草稿;
                Entity.WorkflowStatus = WorkflowStatus.待提交;
                var result = await GenerateCodeAsync();
                if (result.Code == 200)
                {
                    Entity.BillCode = result.Data;
                }
                else
                {
                    MSD.AddModelError(" ", $"生成编码异常. {result.Message}");
                    return;
                }
            }
            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Entity.StaffNo;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity is IBill { WorkflowStatus: WorkflowStatus.提交中 })
            {
                var raw = await DC.Set<SysDailyOutFactoryRequestBill>()
                    .AsNoTracking()
                    .FirstOrDefaultAsync(e => e.ID == Entity.ID);
                if (raw.WorkflowStatus != WorkflowStatus.待提交)
                {
                    MSD.AddModelError(" ", "单据已提交审核,请勿重复提交.");
                    return;
                }
                var result = await StartWorkflowAsync("出厂申请流程");
                if (result == null) return;
                if (!result.Executed)
                {
                    MSD.AddModelError(" ", $"提交审核异常. {result.Exception?.Message}");
                    return;
                }
                Entity.BillStatus = BillStatus.正文;
                Entity.WorkflowStatus = WorkflowStatus.审核中;
            }
            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }
            await base.DoEditAsync(updateAllFields);
        }
        
        /// <summary>
        /// 必须使用异步事务, 否则工作流引擎会和当前事务冲突
        /// </summary>
        /// <param name="upAllFields"></param>
        public async Task ApproveAsync(bool upAllFields = false)
        {
            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(10) // 增加超时时间到10分钟
                },
                TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                if (Entity.BillStatus == BillStatus.草稿) Entity.BillStatus = BillStatus.正文;
                Entity.Approver = Wtm.LoginUserInfo?.ITCode;
                Entity.ApprovalTime = DateTime.Now;
                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    var result = await ContinueWorkflowAsync(ActionName, Remark, "出厂申请流程");
                    if (result.Executed == true)
                    {
                        transactionScope.Complete(); // 提交事务
                    }
                    else
                    {
                        MSD.AddModelError(" ", $"工作流执行失败");
                    }
                }
                // 如果到这里，事务会自动回滚
            }
            catch (Exception e)
            {
                // TransactionScope会自动回滚，无需手动操作
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
        }
        
        /// <summary>
        /// 生成编码
        /// </summary>
        /// <returns></returns>
        public async Task<Result<string>> GenerateCodeAsync()
        {
            if (Entity is IBill bill)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var service = scope.ServiceProvider.GetRequiredService<CodeGeneratorService>();
                var code = await service.GenerateCodeAsync(Entity.GetType().Name);
                return new Result<string>()
                {
                    Data = code
                };
            }
            return new Result<string>("实体未实现IBill接口");
        }
        /// <summary>
        /// 预测编码
        /// </summary>
        /// <returns></returns>
        public async Task<Result<string>> PredictCodeAsync()
        {
            if (Entity is IBill bill)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var service = scope.ServiceProvider.GetRequiredService<CodeGeneratorService>();
                var code = await service.PreviewNextCodeAsync(Entity.GetType().Name);
                return new Result<string>()
                {
                    Data = code
                };
            }
            return new Result<string>("实体未实现IBill接口");
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}
